/*+***********************************
Filename: vectors.s
Description: reset entry.
Modification:
2023.04.21 hzheng creation
2023.08.02 hzheng add isr
2023.08.19 modify push_reg&pop_reg, follow TaskContext structure

************************************-*/

.macro push_reg
    addi  sp, sp, -(32 * 4)
    ##offset 0: sp
    sw sp, 0 * 4(sp)
    sw tp, 1 * 4(sp)
    sw t6, 2 * 4(sp)
    sw t5, 3 * 4(sp)
    sw t4, 4 * 4(sp)
    sw t3, 5 * 4(sp)
    sw t2, 6 * 4(sp)
    sw t1, 7 * 4(sp)
    sw t0, 8 * 4(sp)
    sw s11, 9 * 4(sp)
    sw s10, 10 * 4(sp)
    sw s9, 11 * 4(sp)
    sw s8, 12 * 4(sp)
    sw s7, 13 * 4(sp)
    sw s6, 14 * 4(sp)
    sw s5, 15 * 4(sp)
    ##offset 16: mstatus
    ##offset 17: mepc
    sw a7, 18 * 4(sp)
    sw a6, 19 * 4(sp)
    sw a5, 20 * 4(sp)
    sw a4, 21 * 4(sp)
    sw a3, 22 * 4(sp)
    sw a2, 23 * 4(sp)
    sw a1, 24 * 4(sp)
    sw a0, 25 * 4(sp)
    sw s4, 26 * 4(sp)
    sw s3, 27 * 4(sp)
    sw s2, 28 * 4(sp)
    sw s1, 29 * 4(sp)
    sw s0, 30 * 4(sp)
    sw ra, 31 * 4(sp)
.endm

.macro pop_reg
    ##offset 0: sp
    lw tp, 1 * 4(sp)
    lw t6, 2 * 4(sp)
    lw t5, 3 * 4(sp)
    lw t4, 4 * 4(sp)
    lw t3, 5 * 4(sp)
    lw t2, 6 * 4(sp)
    lw t1, 7 * 4(sp)
    lw t0, 8 * 4(sp)
    lw s11, 9 * 4(sp)
    lw s10, 10 * 4(sp)
    lw s9, 11 * 4(sp)
    lw s8, 12 * 4(sp)
    lw s7, 13 * 4(sp)
    lw s6, 14 * 4(sp)
    lw s5, 15 * 4(sp)
    ##offset 16: mstatus
    ##offset 17: mepc
    lw a7, 18 * 4(sp)
    lw a6, 19 * 4(sp)
    lw a5, 20 * 4(sp)
    lw a4, 21 * 4(sp)
    lw a3, 22 * 4(sp)
    lw a2, 23 * 4(sp)
    lw a1, 24 * 4(sp)
    lw a0, 25 * 4(sp)
    lw s4, 26 * 4(sp)
    lw s3, 27 * 4(sp)
    lw s2, 28 * 4(sp)
    lw s1, 29 * 4(sp)
    lw s0, 30 * 4(sp)
    lw ra, 31 * 4(sp)
    addi  sp, sp, 32 * 4
.endm

     
## reset entry section
##
    .section .text.entry
    .global _start
    .type _start, @function
_start:
## set led on
    lui  a5,0x50006
    li      s0,4
    sh      s0,4(a5)   #GPIO_DIR=0x50006004
    li      s0,4       #0 or 4
    sh      s0,0(a5)   #GPIO_ODR=0x50006000

## shutdown watchdog
    lui a4,0x50000       #0x5000_0048
    lhu a5,48(a4)
    slli    a5,a5,0x10
    srli    a5,a5,0x10
    andi    a5,a5,-2
    slli    a5,a5,0x10
    srli    a5,a5,0x10
    sh  a5,48(a4)

## set sp
    la sp, __SYSTEM_STACK_END__

## set interrupt vector
    la t0, trap_vector
    csrw	mtvec,t0

## enable interrupt
    li t0, 0x888
    csrw mie,t0
    
## enable global mie
    csrsi  mstatus,0x08
    
## call main
    la     t0, main
    jalr   t0
    
## dead_loop
    j .  

    
## isr
    .global myisr

    .type isr_wrapper, @function
isr_wrapper:
    push_reg
    la     t0, myisr
    jalr   t0
    pop_reg
    mret
    
## trap_vector
    .align 2
trap_vector:
    j isr_wrapper
